package com.frinder.official.akka.actors;

import akka.actor.*;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Created by frinder on 2017/9/13.
 * <p>
 * 注：实例实现由 ActorSelection 获取 ActorRef 的一种方式
 */
@Component
@Scope("prototype")
public class Follower extends AbstractActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);

    final String myActor = "follower-my-actor";
    final Integer identifyId = 1;

    @Override
    public void preStart() throws Exception {
        super.preStart();
        ActorSelection selection = getContext().actorSelection(String.format("/user/%s", myActor));
        selection.tell(new Identify(identifyId), getSelf());
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(ActorIdentity.class, id -> id.getActorRef().isPresent(), id -> {
                    log.debug("Received ActorIdentity message: {}", id);
                    ActorRef ref = id.getActorRef().get();
                    getContext().watch(ref);
                    getContext().become(active(ref));
                })
                .match(ActorIdentity.class, id -> !id.getActorRef().isPresent(), id -> {
                    log.error("Received ActorIdentity message: {}", id);
                    getContext().stop(getSelf());
                })
                .build();
    }

    final Receive active(final ActorRef another) {
        return receiveBuilder()
                .match(Terminated.class, t -> t.actor().equals(another), t ->

                        getContext().stop(getSelf())
                )
                .build();
    }

}